package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/logger"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-plugins/registry/consul/v2"
	"user/common"
	"user/domain/repository"
	service2 "user/domain/service"
	"user/handler"
	user "user/proto"
)

func main() {

	// 配置中心
	consulConfig, err := common.GetConsulConfig()
	if err != nil {
		logger.Fatal(err)
	}

	// Mysql配置信息
	mysqlInfo, err := common.GetMysqlFromConsul(consulConfig, "mysql")
	if err != nil {
		logger.Fatal(err)
	}
	logger.Info("Mysql配置信息:", mysqlInfo)

	//注册中心
	consul := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{
			"consul.topwhere.cn:80",
		}
	})

	//链路追踪
	//t, io, err := common.NewTracer("user", "pjaeger.topwhere.cn:80")
	//if err != nil {
	//	logger.Fatal(err)
	//}
	//defer io.Close()
	//opentracing.SetGlobalTracer(t)

	//创建数据库
	db, err := gorm.Open("mysql", mysqlInfo.User+":"+mysqlInfo.Pwd+"@tcp("+mysqlInfo.Host+":3306)/"+mysqlInfo.Database+"?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
		fmt.Println("连接数据库失败")
	}
	defer db.Close()
	db.SingularTable(true)
	//创建表（只执行一次）
	rp := repository.NewUserRepository(db)
	rp.InitTable()

	userDataService := service2.NewUserDataService(repository.NewUserRepository(db))

	//1. 创建新的服务
	// Create service
	service := micro.NewService(
		micro.Name("user"),
		micro.Version("latest"),
		//micro.Address("0.0.0.0:8089"),
		//添加注册中心
		micro.Registry(consul),
		//绑定链路追踪
		//micro.WrapHandler(opentracing2.NewHandlerWrapper(opentracing.GlobalTracer())),
	)

	//2. 初始化方法
	service.Init()

	//3. 注册服务
	// Register handler
	err = user.RegisterUserHandler(service.Server(), &handler.User{UserDataService: userDataService})
	if err != nil {
		fmt.Println(err)
	}

	//4.运行服务
	// Run service
	if err := service.Run(); err != nil {
		logger.Fatal(err)
	}
}
